# -- coding:utf-8 --
# 腾讯会议
import requests
import hmac
import base64
import hashlib
import time
import random
import json
import qrcode

class TencentConference(object):

    def __init__(self):

        self.app_id = '224126669'
        self.sdk_id = '22800175764'
        self.secret_id = 'rFCM8OeTR5Z0BmcNZ21jNxZHmcXiBtZD'
        self.secret_key = 'sFdg42ObBcRi16LO30QiNySVroyr8owylNxPWGAc9uqQn218'
        self.tody_time = str(int(time.time()))
        self.nonce = str(int(random.random() * 10000))
        self.headers = {
            "X-TC-Key": self.secret_id,
            "X-TC-Timestamp": self.tody_time,
            "X-TC-Nonce": self.nonce,
            "X-TC-Signature": '',
            "AppId": self.app_id,
            "SdkId": self.sdk_id,
            "X-TC-Registered": "1"
        }

    def get_sign(self, method, uri, params, nonce1, time1):  # 生成签名

        try:

            header_string = "X-TC-Key=" + self.secret_id + "&X-TC-Nonce=" + nonce1 + "&X-TC-Timestamp=" + time1

            data = method + "\n" + header_string + "\n" + uri + "\n" + params

            data = bytes(data.encode('utf-8'))

            key = self.secret_key.encode('utf-8')

            return (base64.b64encode((hmac.new(key, data, digestmod=hashlib.sha256).hexdigest()).encode('utf-8'))). \
                decode('utf-8')

        except Exception as e:
            print(e)
            return False

    # 创建
    def crate_wrok(self, userid, instanceid, subject, types, start_time_, end_time_, password):

        try:

            uri = '/v1/meetings'

            params = json.dumps({
                "userid": userid,  # 用户id
                "instanceid": instanceid,  # 用户的终端设备类型 1 PC
                "subject": subject,  # 会议主题
                "type": types,  # 会议类型 0 预约会议   1快速会议
                "start_time": start_time_,  # 会议开始时间戳 单位秒
                "end_time": end_time_,  # 会议结束时间戳 单位秒
                "password": password  # 会议密码
            })

            signa_ture = self.get_sign('POST', uri, params, self.nonce, self.tody_time)

            self.headers['X-TC-Signature'] = signa_ture
            print(self.headers, '*-*')

            get_data = requests.post("https://api.meeting.qq.com" + uri, headers=self.headers, data=params)
            print(get_data.json())

            return get_data.json()

        except Exception as e:

            print(e)
            return False

    def get_wrok(self, ids):  # 查询会议状态
        # id 会议id
        try:

            uri = '/v1/meetings'

            signa_ture = self.get_sign('POST', uri, '', self.nonce, self.tody_time)

            self.headers['X-TC-Signature'] = signa_ture

            get_data = requests.get("https://api.meeting.qq.com" + uri + str(ids), headers=self.headers)
            print(get_data.json())

            return get_data.json()

        except Exception as e:

            print(e)
            return False

    def cancel_wrok(self, ids, userid, instanceid, reason_code, reason_detail):  # 取消会议
        # id 会议id

        try:
            uri = '/v1/meetings'
            params = json.dumps({
                "userid": userid,  # 用户id         String
                "instanceid": instanceid,  # 用户的终端设备类型 1 PC    Integer
                "reason_code": reason_code,  # 原因代码，可为用户自定义。   Integer
                "reason_detail": reason_detail,  # 详细取消原因描述。   String
            })
            signa_ture = self.get_sign('POST', uri, '', self.nonce, self.tody_time)
            self.headers['X-TC-Signature'] = signa_ture
            get_data = requests.post("https://api.meeting.qq.com" + uri + str(ids) + '/cancel', headers=self.headers,
                                     data=params)
            print(get_data.json())
            return get_data.json()
        except Exception as e:

            print(e)
            return False

    # 获取开课列表
    def get_work_list(self, userid):

        try:

            uri = f"/v1/meetings?userid={userid}&instanceid=1"

            signa_ture = self.get_sign('GET', uri, '', self.nonce, self.tody_time)

            self.headers['X-TC-Signature'] = signa_ture

            get_data = requests.get("https://api.meeting.qq.com" + uri, headers=self.headers)
            print(get_data.json())

        except Exception as e:

            print(e)
            return False

    def crate_user(self, phone, username, userid):

        try:

            uri = '/v1/users'

            params = json.dumps({
                "userid": userid,  # 用户id  唯一标识
                "phone": phone,  # 用户 手机号
                "username": username,  # 用户昵称
            })

            signa_ture = self.get_sign('POST', uri, params, self.nonce, self.tody_time)

            self.headers['X-TC-Signature'] = signa_ture
            print(self.headers, '*-*')

            get_data = requests.post("https://api.meeting.qq.com" + uri, headers=self.headers, data=params)
            print(get_data.json())

            return get_data.json()

        except Exception as e:

            print(e)
            return False

    # user list  用户列表
    def get_user_list1(self, pagev, page_sizev):
        try:

            uri = f"/v1/users/list?page={pagev}&page_size={page_sizev}"

            signa_ture = self.get_sign('GET', uri, '', self.nonce, self.tody_time)

            self.headers['X-TC-Signature'] = signa_ture

            get_data = requests.get("https://api.meeting.qq.com" + uri, headers=self.headers)
            print(get_data.json())

            data_count = get_data.json()

            return data_count['total_count']

        except Exception as e:

            print(e)
            return False

    # room list 房间列表
    def get_room_list(self, pagev, page_sizev, meeting_room_namev):

        try:

            uri = "/v1/meeting-rooms?page={page}&page_size={page_size}&meeting_room_name={meeting_room_name}".format(
                meeting_room_name=meeting_room_namev, page_size=page_sizev, page=pagev)

            signa_ture = self.get_sign('GET', uri, '', self.nonce, self.tody_time)

            self.headers['X-TC-Signature'] = signa_ture

            get_data = requests.get("https://api.meeting.qq.com" + uri, headers=self.headers)
            print(get_data.json())

            data_count = get_data.json()

            return data_count['total_count']

        except Exception as e:

            print(e)
            return False

    # 查询账户下 Rooms 资源
    def get_room_inventory(self):

        try:

            uri = "/v1/rooms-inventory"

            signa_ture = self.get_sign('GET', uri, '', self.nonce, self.tody_time)

            self.headers['X-TC-Signature'] = signa_ture
            print('headers:', self.headers)

            get_data = requests.get("https://api.meeting.qq.com" + uri, headers=self.headers)
            print(get_data.json())

            return get_data.json()

        except Exception as e:

            print(e)
            return False

    def time_transition(self, time_):

        timearray = time.strptime(time_, "%Y-%m-%d %H:%M:%S")

        time_ = str(int(time.mktime(timearray)))

        return time_
    def generate_or_code(self,url):
        try:
            img = qrcode.make(url)
            path = f'../static/QR_code/img{time.time()}.png'
            img.save(path)

            return path

        except Exception as e:
            print(e)
            return False

# 初始化类对象
t = TencentConference()

start_time = t.time_transition('2023-5-24 15:50:00')
end_time = t.time_transition('2023-5-24 23:40:00')

# 创建用户       手机号  昵称  uid
# t.crate_user('18317565345', '周', '18317565345')

# 调用创建会议
t.crate_wrok(userid='18317565345', instanceid=1, subject="Ceshi2", types=0, start_time_=start_time, end_time_=end_time,
             password='123456')

# 生成二维码
# t.generate_or_code('https://meeting.tencent.com/dm/Vz9FYLnvRD7C')
















